package com.neusoft.elmboot.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.elmboot.dto.UserDTO;
import com.neusoft.elmboot.mapper.UserMapper;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.UserService;
import com.neusoft.elmboot.util.EncryptionUtil;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDTO getUserByIdByPass(User user) {
        // 查询用户信息
        User result = userMapper.getUserById(user.getUserId());
        if (result != null) {
            // 使用 BCrypt 验证密码
            if (EncryptionUtil.checkPassword(user.getPassword(), result.getPassword())) {
                return convertToDTO(result);
            }
        }
        return null;  // 如果密码不匹配，返回 null
    }



    @Override
    public User getUserById(String userId) {
        return userMapper.getUserById(userId);
    }

    @Override
    public int saveUser(User user) {
        // 对用户输入的密码进行加密
        String encryptedPassword = EncryptionUtil.encryptPassword(user.getPassword());
        user.setPassword(encryptedPassword);
        return userMapper.saveUser(user);
    }

    private UserDTO convertToDTO(User user) {
        if (user == null) {
            return null;
        }
        UserDTO dto = new UserDTO();
        dto.setUserId(user.getUserId());
        dto.setUserName(user.getUserName());
        dto.setUserSex(user.getUserSex());
        dto.setUserImg(user.getUserImg() == null ? "" : user.getUserImg());
        // 不返回密码等敏感信息
        return dto;
    }

}
